package com.alexwan.asynctaskdemo;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class AsyncTaskActivity extends Activity implements OnClickListener
{
    private Button mExecuteBtn, mCancelBtn;
    
    private TextView mTextView;
    
    private ProgressBar mProgressBar;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task);
        mExecuteBtn = (Button) findViewById(R.id.excute_btn);
        mExecuteBtn.setOnClickListener(this);
        mCancelBtn = (Button) findViewById(R.id.cancel_btn);
        mCancelBtn.setOnClickListener(this);
        mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
        mTextView = (TextView) findViewById(R.id.text_view);
    }
    
    private GetAsyncTask task;
    
    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.excute_btn:
                task = new GetAsyncTask();
                task.execute("http://www.baidu.com");
                mExecuteBtn.setClickable(false);
                mCancelBtn.setClickable(true);
                break;
            case R.id.cancel_btn:
                if (task != null)
                {
                    task.cancel(true);
                }
                break;
            
            default:
                break;
        }
    }
    
    private class GetAsyncTask extends AsyncTask<String, Integer, String>
    {
        
        @Override
        protected void onPreExecute()
        {
            //task执行前的UI
            mTextView.setText("loading...");
        }
        
        @Override
        protected String doInBackground(String... params)
        {
            //后台处理耗时任务，这里不能修改UI
//            InputStream is = null;
//            HttpURLConnection connection = null;
//            ByteArrayOutputStream bos = null;
//            try
//            {
//                connection = (HttpURLConnection) new URL(params[0]).openConnection();
//                connection.setRequestMethod("POST");
//                connection.setDoOutput(true);
//                connection.setUseCaches(false);
//                int code = connection.getResponseCode();
//                Log.i("alexwan--------asynctask",
//                        "connection.getResponseCode() : " + code);
//                if (code == 200)
//                {
//                    int total = connection.getContentLength();
//                    is = connection.getInputStream();
//                    bos = new ByteArrayOutputStream();
//                    byte[] buf = new byte[1024];
//                    int length = -1;
//                    if ((length = is.read(buf)) != -1)
//                    {
//                        bos.write(buf, 0, length);
//                        publishProgress((int) ((length / (float) total) * 100));
//                        Thread.sleep(100);
//                    }
//                    return new String(bos.toByteArray(), "utf-8");
//                }
//            }
//            catch (Exception e)
//            {
//                e.printStackTrace();
//            }
//            finally
//            {
//                try
//                {
//                    if (bos != null)
//                    {
//                        
//                        bos.close();
//                        
//                    }
//                    if (is != null)
//                    {
//                        is.close();
//                    }
//                }
//                catch (IOException e)
//                {
//                    e.printStackTrace();
//                }
//            }
            try
            {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(params[0]);
                HttpResponse response = client.execute(post);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
                {
                    HttpEntity entity = response.getEntity();
                    InputStream is = entity.getContent();
                    long total = entity.getContentLength();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024];
                    int count = 0;
                    int length = -1;
                    while ((length = is.read(buf)) != -1)
                    {
                        baos.write(buf, 0, length);
                        count += length;
                        //调用publishProgress公布进度,最后onProgressUpdate方法将被执行  
                        publishProgress((int) ((count / (float) total) * 100));
                        //为了演示进度,休眠500毫秒  
                    }
                    return new String(baos.toByteArray(), "utf-8");
                }
            }
            catch (Exception e)
            {
                Log.e("alexwan---------exception", e.getMessage());
            }
            return null;
        }
        
        @Override
        protected void onPostExecute(String result)
        {
            //task执行的结果
            mTextView.setText(result);
            mExecuteBtn.setClickable(true);
            mCancelBtn.setClickable(false);
        }
        
        @Override
        protected void onProgressUpdate(Integer... values)
        {
            //在调用publishProgress()方法之后,执行
            //更新进度条
            mTextView.setText("loading - " + values[0] + " %");
            mProgressBar.setProgress(values[0]);
        }
        
        @Override
        protected void onCancelled()
        {
            //
            mProgressBar.setProgress(0);
            mTextView.setText("");
            mExecuteBtn.setClickable(true);
            mCancelBtn.setClickable(false);
        }
        
    }
}
